﻿using HtmlAgilityPack;
using MijnMultiOSRSSApp.Common.Helpers;
using MijnMultiOSRSSApp.Common.Models;
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;

namespace MijnMultiOSRSSApp.Common.Converters
{
    public class HtmlToTextConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value == null || !(value is RSSItem))
                return null;

            var paragraphs = new List<TextBlock>();
            var item = value as RSSItem;
            var content = item.Description != null ? item.Description : string.Empty;

            var document = new HtmlDocument();
            document.LoadHtml(HtmlParser.CleanupText(HtmlParser.StripHTMLTags(content)));
            foreach (var element in document.DocumentNode.ChildNodes)
            {
                if (!string.IsNullOrWhiteSpace(element.InnerText))
                {
                    var paragraphText = element.InnerHtml;
                    paragraphText = HtmlParser.ExtractString(paragraphText);
                    paragraphText = paragraphText.Trim();

                    if (string.IsNullOrEmpty(paragraphText))
                        continue;

                    paragraphs.Add(new TextBlock
                    {
                        Text = paragraphText,
                        TextWrapping = TextWrapping.Wrap,
                        Style = (Style)Application.Current.Resources["PhoneTextNormalStyle"],
                        Margin = new Thickness(12, 0, 12, 12)
                    });
                }
            }

            return paragraphs;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
